package com.ikun.kunpicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikun.kunpicturebackend.domain.User;
import com.ikun.kunpicturebackend.exception.BusinessException;
import com.ikun.kunpicturebackend.exception.ErrorCode;
import com.ikun.kunpicturebackend.exception.ThrowUtils;
import com.ikun.kunpicturebackend.manager.auth.StpKit;
import com.ikun.kunpicturebackend.model.dto.user.UserQueryRequest;
import com.ikun.kunpicturebackend.model.enums.UserRoleEnum;
import com.ikun.kunpicturebackend.model.vo.LoginUserVO;
import com.ikun.kunpicturebackend.model.vo.UserVO;
import com.ikun.kunpicturebackend.service.UserService;
import com.ikun.kunpicturebackend.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

import static com.ikun.kunpicturebackend.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author 32144
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-09-21 17:20:17
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //1. 参数校验，不能为空，长度校验
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword, checkPassword),
                ErrorCode.PARAMS_ERROR, "参数不能为空");
        //1.1 校验账号长度
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR, "用户账号过短");
        //1.2 校验密码长度
        ThrowUtils.throwIf(userPassword.length() < 8 || checkPassword.length() < 8, ErrorCode.PARAMS_ERROR, "密码长度过短");
        //1.3 检验两次输入是否一致
        ThrowUtils.throwIf(!userPassword.equals(checkPassword), ErrorCode.PARAMS_ERROR, "两次输入密码不一致");

        //2. 检查账号是否重复
        //2.1 封装查询条件，账号是唯一的
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        Long count = baseMapper.selectCount(queryWrapper);
        //2.2 用户存在
        ThrowUtils.throwIf(count > 0, ErrorCode.PARAMS_ERROR, "账号已存在");

        //3. 密码加密
        String encryptPassword = getEncryptPassword(userPassword);

        //4. 插入数据
        //4.1 数据封装
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        //4.2 普通用户
        user.setUserRole(UserRoleEnum.USER.getValue());
        user.setUserName("爱坤");

        boolean result = save(user);

        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        return user.getId();
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 参数校验
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword),
                ErrorCode.PARAMS_ERROR, "参数不能为空");
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR, "账号错误");
        ThrowUtils.throwIf(userPassword.length() < 8, ErrorCode.PARAMS_ERROR, "密码错误");

        // 2. 获取加密的密码
        String encryptPassword = getEncryptPassword(userPassword);

        // 3. 查询用户是否存在
        // 3.1 构造查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount).eq("userPassword", encryptPassword);
        // 3.2 查询并判断用户是否存在
        User user = baseMapper.selectOne(queryWrapper);
        if (user == null) {
            log.info("登录失败，用户不存在或密码错误");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }

//        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        // 4.将用户信息写入session
        request.getSession().setAttribute(USER_LOGIN_STATE, user);

        // 记录用户登录态到Sa-token,便于空间鉴权时使用。
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(USER_LOGIN_STATE, user);
        return BeanUtil.copyProperties(user, LoginUserVO.class);
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        //1. 从session中获取用户信息，判断是否登录
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        //1.1 未登录
        ThrowUtils.throwIf(user == null || user.getId() == null, ErrorCode.NOT_LOGIN_ERROR);
        //2. 获取用户id从数据库查询最新的信息
        Long id = user.getId();
        User loginUser = this.getById(id);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        return loginUser;
    }

    @Override
    public Boolean userLogOut(HttpServletRequest request) {
        Object user = request.getSession().getAttribute(USER_LOGIN_STATE);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);
        //从session中移除
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    /**
     * 密码加密
     * @param password 密码
     * @return 加密密码
     */
    public String getEncryptPassword(String password) {
        //加盐
        final String SALT = "ikun";
        return DigestUtils.md5DigestAsHex((password + SALT).getBytes());
    }

    /**
     * 构造QueryWrapper
     * @param request
     * @return
     */
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR, "参数为空");
        Long id = request.getId();
        String userName = request.getUserName();
        String userAccount = request.getUserAccount();
        String userProfile = request.getUserProfile();
        String userRole = request.getUserRole();
        String sortField = request.getSortField();
        String sortOrder = request.getSortOrder();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id)
                .eq(StrUtil.isNotBlank(userRole), "userRole", userRole)
                .like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount)
                .like(StrUtil.isNotBlank(userName), "userName", userName)
                .like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile)
                .orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

}




